package com.quectel.cms.controller.securitypatrol;


import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolTaskDto;
import com.quectel.core.module.securitypatrol.service.SecurityPatrolTaskService;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/05/07 14:10
 */
@RestController
@RequestMapping("securityPatrolTask")
@Tag(name = "SecurityPatrolTaskController", description = "视频巡逻任务相关api")
public class SecurityPatrolTaskController extends BaseController {

    @DubboReference
    private SecurityPatrolTaskService securityPatrolTaskService;

    /**
     * 导出巡检任务为excel
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "securityPatrolTask:exportExcel")
    @Log(express = "导出巡检任务为excel")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        List<SecurityPatrolTaskDto> result = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 1000);
        while (true) {
            params.put("offset", pageNo++ * 1000);
            List<SecurityPatrolTaskDto> list = securityPatrolTaskService.queryList(params);
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                break;
            }
            result.addAll(list);
            if (list.size() < 1000) {
                break;
            }
        }
        String[] headers = new String[]{"所属小区", "任务名称", "任务路线", "任务日期", "执行时段", "巡检人", "任务状态", "生成时间", "完成时间"};
        List<String[]> dataList = new ArrayList<>();
        for (SecurityPatrolTaskDto data : result) {
            String[] item = new String[headers.length];
            item[0] = data.getVillageName();
            item[1] = data.getName();
            item[2] = data.getPlanName();
            item[3] = data.getDate();
            item[4] = data.getPeriod();
            item[5] = data.getExecUsername();
            item[6] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.PATROL_EXECUTION_STATUS, String.valueOf(data.getExecStatus()));
            item[7] = data.getCreateTime() != null ? DateUtils.format(data.getCreateTime(), DateUtils.FormatType.COMMON) : null;
            item[8] = data.getCompleteTime() != null ? DateUtils.format(data.getCompleteTime(), DateUtils.FormatType.COMMON) : null;
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "安保巡检-巡检任务", headers, dataList, "巡检任务信息");

    }


    /**
     * 视频巡逻任务分页查询列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "securityPatrolTask:list")
    @Operation(summary = "视频巡逻任务分页查询列表")
    public Response<Page<SecurityPatrolTaskDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = securityPatrolTaskService.queryTotal(request.getParams());

        List<SecurityPatrolTaskDto> list = null;
        if (total > 0) {
            list = securityPatrolTaskService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<SecurityPatrolTaskDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<SecurityPatrolTaskDto>>ok().wrap(page);
    }


    /**
     * 查询视频巡逻任务单条记录，编辑反显查询
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "securityPatrolTask:edit")
    @Operation(summary = "查询视频巡逻任务单条记录，编辑反显查询")
    public Response<SecurityPatrolTaskDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (securityPatrolTaskService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SecurityPatrolTaskDto securityPatrolTaskDto = securityPatrolTaskService.selectById(id);

        return Response.<SecurityPatrolTaskDto>ok().wrap((securityPatrolTaskDto));
    }

    /**
     * 查询视频巡逻任务单条记录
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "securityPatrolTask:info")
    @Operation(summary = "查询视频巡逻任务单条记录")
    public Response<SecurityPatrolTaskDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (securityPatrolTaskService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SecurityPatrolTaskDto securityPatrolTaskDto = securityPatrolTaskService.selectById(id);

        return Response.<SecurityPatrolTaskDto>ok().wrap((securityPatrolTaskDto));
    }

    /**
     * 保存视频巡逻任务单条记录
     */
    @PostMapping("save")
    @RequirePermissions(values = "securityPatrolTask:edit")
    @Operation(summary = "保存视频巡逻任务单条记录")
    public Response<Object> save(@RequestBody @Validated SecurityPatrolTaskDto securityPatrolTaskDto) {

        //填充基础数据
        fillSaveCommonData(securityPatrolTaskDto);

        securityPatrolTaskService.save(securityPatrolTaskDto);

        return Response.ok();
    }

    /**
     * 修改视频巡逻任务单条记录
     */
    @PostMapping("update")
    @RequirePermissions(values = "securityPatrolTask:edit")
    @Operation(summary = "修改视频巡逻任务单条记录")
    public Response<Object> update(@RequestBody @Validated SecurityPatrolTaskDto securityPatrolTaskDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(securityPatrolTaskDto.getId()));
        if (securityPatrolTaskService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(securityPatrolTaskDto);

        securityPatrolTaskService.updateById(securityPatrolTaskDto);

        return Response.ok();
    }

    /**
     * 批量删除视频巡逻任务单条记录
     */
    @PostMapping("delete")
    @RequirePermissions(values = "securityPatrolTask:delete")
    @Operation(summary = "批量删除视频巡逻任务单条记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (securityPatrolTaskService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        securityPatrolTaskService.deleteBatch(ids);

        return Response.ok();
    }
}
